package cn.wolfcode.mycat.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.apache.http.HttpHost;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Properties;

@Slf4j
public class PropertyUtil {

	private final static String CONF_NAME = "config.properties";

	private static Properties contextProperties;

	static {
		InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(CONF_NAME);
		contextProperties = new Properties();
		try {
			InputStreamReader inputStreamReader = new InputStreamReader(in, "UTF-8");
			contextProperties.load(inputStreamReader);
		} catch (IOException e) {
			log.error("资源文件加载失败! e={}", e);
		}
		log.info("资源文件加载成功");
	}

	public static String getStrValue(String key) {
		return contextProperties.getProperty(key);
	}

	public static int getIntValue(String key) {
		String strValue = getStrValue(key);
		return Integer.parseInt(strValue);
	}

	public static Properties getKafkaProperties(String groupId) {
		Properties properties = new Properties();
		properties.setProperty("bootstrap.servers", getStrValue("kafka.bootstrap.servers"));
		properties.setProperty("zookeeper.connect", getStrValue("kafka.zookeeper.connect"));
		properties.setProperty("group.id", groupId);
		return properties;
	}
	
	public static List<HttpHost> getEsHttpHost() {
		List<HttpHost> httpHosts = Lists.newArrayList();
		String redisClusterHosts = PropertyUtil.getStrValue("es.cluster");
		for (String host : redisClusterHosts.split(",")) {
			String[] ipPort = host.split(":");
			HttpHost httpHost = new HttpHost(ipPort[0], Integer.valueOf(ipPort[1]));
			httpHosts.add(httpHost);
		}
		return httpHosts;
	}
	
	public static void main(String[] args) {
		System.out.println(PropertyUtil.getStrValue("rocketmq.nameserver.addr"));
	}

}
